import { Controller, GET, AbstractController } from 'fastify-decorators'
import { FastifyReply, FastifyRequest } from 'fastify'
import * as path from 'path'
import * as pug from 'pug'
import * as fs from 'fs'
@Controller({ route: '/plugins' })
export default class PluginsController extends AbstractController {
  @GET({ url: '/:plugin' })
  public indexAction(request: FastifyRequest<any>, reply: FastifyReply<any>) {
    const plugins = this.instance.plugins()
    const plugin = request.params.plugin
    const target = plugins.find(x => x.pluginPath === plugin)

    if (!target) {
      reply.callNotFound()
    }

    const htmlTemplate = fs.readFileSync(path.resolve('public', 'plugins', target.pluginPath, 'index.html'), 'utf8')
    // 生成客户端配置信息
    const clientConfig = this.getClientConfig(request)

    // 显示模版页面
    reply.view('templates/index.pug', {
      plugins,
      target,
      content: htmlTemplate,
      clientConfig
    })
  }

  private getClientConfig(request: FastifyRequest<any>) {
    return {
      collapse: request.query.collapse === 'true',
      currentDate: this.instance.config.CURRENT_DATE || new Date()
    }
  }
}
